package com.jinzhi.jzdoor.certificate.controller;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.jinzhi.api.exception.IFastApiException;
import com.jinzhi.api.pojo.vo.TokenVO;
import com.jinzhi.common.annotation.Log;
import com.jinzhi.common.base.BaseController;
import com.jinzhi.common.domain.DictDO;
import com.jinzhi.common.service.DictService;
import com.jinzhi.common.type.ApiEnumError;
import com.jinzhi.common.type.EnumErrorCode;
import com.jinzhi.common.utils.*;
import com.jinzhi.jzapi.certificate.pojo.ExpertsVo;
import com.jinzhi.jzdoor.certificate.pojo.TrainingBaseVo;
import com.jinzhi.jzweb.domain.*;
import com.jinzhi.jzweb.pojo.ErroeDownVo;
import com.jinzhi.jzweb.pojo.ErrorCodeVo;
import com.jinzhi.jzweb.service.*;
import com.jinzhi.jzweb.utils.EasyPoiUtil;
import com.jinzhi.sms.support.SmsManager;
import com.jinzhi.sys.domain.UserDO;
import com.jinzhi.sys.service.UserService;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.apache.shiro.crypto.hash.Sha256Hash;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.util.*;

import static com.jinzhi.api.util.TokenTag.TOKEN_TAG;

@Slf4j
@Controller
@AllArgsConstructor
@RequestMapping("/certificate")
public class IndexController extends BaseController {

    @Autowired
    private ConsultationsService consultationsService;
    @Autowired
    private CertificateNewsService certificateNewsService;
    @Autowired
    private CertificateProfileService certificateProfileService;
    @Autowired
    private ExaminationPointService examinationPointService;
    @Autowired
    private UserService userService;
    @Autowired
    private OrganizationNewsService organizationNewsService;
    @Autowired
    private ExpertsService expertsService;
    @Autowired
    private CertificationBatchService certificationBatchService;
    @Autowired
    private ExaminationBatchService examinationBatchService;
    @Autowired
    private ExaminationResultsService examinationResultsService;
    @Autowired
    private OrganizationRolesService organizationRolesService;
    @Autowired
    private KnowledgePointsService knowledgePointsService;
    @Autowired
    private SmsManager smsService;
    @Autowired
    private StuSignUpService stuSignUpService;
    @Autowired
    private MessageplatfromService messageplatfromService;
    @Autowired
    private MsgService msgService;
    @Autowired
    private OrgRelationService orgRelationService;
    @Autowired
    private DictService dictService;
    @Autowired
    private TrainInfoService trainInfoService;
    @Autowired
    private InfoStoreService infoStoreService;
    @Autowired
    private InfoModelService infoModelService;
    @Autowired
    private InfoCollectService infoCollectService;
    @Autowired
    private  PeixunStudyService peixunStudyService;
    @Autowired
    private ResumesService resumesService;
    @Autowired
    private PeixResumeCollectService peixResumeCollectService;

    @Autowired
    private LeavingAMessageService leavingAMessageService;

    private static final String T_REG_SMS_PREFIX = "TRAINING_REG_";//培训端
    private static final String C_REG_SMS_PREFIX = "CERTIFICATE_REG_";//证书端
    private static final String O_REG_SMS_PREFIX = "ORTHER_REG_";//其他端


    @Log("证书门户首页")
    @GetMapping("/homepage")
    String homepage() {
        return "certificateWeb/homepage/homepage";
    }


    @Log("证书门户首页")
    @GetMapping("/homepage2")
    String homepage2() {
        return "certificateWeb/homepage/homepage2";
    }


    @Log("企业注册")
    @GetMapping("/enterpriseReg")
    String enterpriseReg(Model model,String id,String mobile,String name,String enId) {
       // UserDO userDO = userService.selectById(id);
        model.addAttribute("id",id);
        model.addAttribute("name",name);
        model.addAttribute("mobile",mobile);
        model.addAttribute("enId",enId);
        return "certificateWeb/enterpriseReg";
    }
    @Log("证书门户通知公告")
    @GetMapping("/inform")
    String inform(Model model) {
        Wrapper<ConsultationsDO> consultationsDOWrapper = new EntityWrapper<ConsultationsDO>().orderBy("creater_date", false);
        consultationsDOWrapper.eq("first_column", "证书考试门户");
        consultationsDOWrapper.eq("state", 1);
        consultationsDOWrapper.eq("second_column", "通知公告");

        List<ConsultationsDO> consultationsDOList = consultationsService.selectList(consultationsDOWrapper);
        model.addAttribute("consultations", consultationsDOList);
        return "certificateWeb/inform/inform";
    }

    @Log("通知公告详情")
    @GetMapping("/informDetail")
    String informDetail(Model model, Long id) {
        ConsultationsDO consultations = consultationsService.selectById(id);
        consultations.setAccessNumber(consultations.getAccessNumber() + 1);
        consultationsService.updateById(consultations);
        model.addAttribute("consultations", consultations);
        return "certificateWeb/inform/informDetail";
    }

    @Log("考务员信息填写")
    @GetMapping("/trainStudentInfo")
    String KWInfo() {
        return "certificateWeb/trainStudentInfo";
    }

    @Log("证书标准信息页面")
    @GetMapping("/certificateInfo")
    String certificateInfo() {
        return "certificateWeb/workNews/certificateInfo";
    }

    @Log("证书标准信息")
    @GetMapping("/selCertificateInfo")
    @ResponseBody
    public Result<?> selCertificateInfo(Model model, String current, String number) {
        Page<CertificateNewsDO> page = certificateNewsService.selectListPagesFormal(Integer.parseInt(current), Integer.parseInt(number));
        List<CertificateNewsDO> certificateNewsDOList = page.getRecords();
        for (CertificateNewsDO certificateNews : certificateNewsDOList) {
            CertificateProfileDO certificateProfile = certificateProfileService.selectById(certificateNews.getProfileId());
            if (certificateProfile != null) {
                certificateNews.setProfileName(certificateProfile.getName());
            }
        }

        page.setRecords(certificateNewsDOList);
        return Result.ok(page);
    }

    @Log("跳转证书简介页面")
    @GetMapping("/standardInfo")
    String standardInfo(Model model) {
        Wrapper<CertificateProfileDO> wrapper = new EntityWrapper<CertificateProfileDO>().orderBy("creater_date", false);
        wrapper.eq("state", 0);
        List<CertificateProfileDO> certificateProfileDO = certificateProfileService.selectList(wrapper);
        model.addAttribute("certificateProfile", certificateProfileDO);
        return "certificateWeb/workNews/standardInfo";
    }

    @Log("证书简介查询")
    @GetMapping("/standardInfoApi")
    @ResponseBody
    Result<?> standardInfoApi(Model model, String current, String number) {
        Page<CertificateProfileDO> page = certificateProfileService.findListPageFormal(Integer.parseInt(current), Integer.parseInt(number));
        return Result.ok(page);
    }

    @Log("行业资讯")
    @GetMapping("/tradeInfo")
    String tradeInfo() {
        return "certificateWeb/tradeInfo/tradeInfo";
    }

    @Log("政策资讯")
    @GetMapping("/policyInfo")
    String policyInfo() {
        return "certificateWeb/tradeInfo/policyInfo";
    }

    @Log("通知通告")
    @GetMapping("/noticeInfo")
    String noticeInfo() {
        return "certificateWeb/tradeInfo/noticeInfo";
    }

    @Log("资讯详情")
    @GetMapping("/policyDetail")
    String policyDetail(Model model, Long id) {
        ConsultationsDO consultationsDO = consultationsService.selectById(id);
        consultationsDO.setAccessNumber(consultationsDO.getAccessNumber() + 1);
        consultationsService.updateById(consultationsDO);
        model.addAttribute("consultations", consultationsDO);
        return "certificateWeb/tradeInfo/policyDetail";
    }

    @Log("证书查询")
    @GetMapping("/certificateQuery")
    String certificateQuery() {
        return "certificateWeb/infoQuery/certificateQuery";
    }

    @Log("培训站点查询")
    @GetMapping("/testingCentreQueryPx")
    String testingCentreQueryPx() {
        return "certificateWeb/infoQuery/trainfoQuery";
    }

    @Log("考点查询")
    @GetMapping("/testingCentreQuery")
    String testingCentreQuery() {
        return "certificateWeb/infoQuery/testingCentreQuery";
    }


    @Log("考点名查询")
    @GetMapping("/testingCentreNameQuery")
    String testingCentreNameQuery(Model model, String name) {

        Wrapper<ExaminationPointDO> wrapper = new EntityWrapper<>();
        wrapper.eq("name", name);
        wrapper.eq("state", 0);

        List<ExaminationPointDO> examinationPointList = examinationPointService.selectList(wrapper);

        for (ExaminationPointDO examinationPoint : examinationPointList) {
            UserDO userDO = userService.selectById(examinationPoint.getUserId());
            examinationPoint.setUName(userDO.getUsername());
            OrganizationNewsDO organizationNews = organizationNewsService.selectById(examinationPoint.getOrgId());
            examinationPoint.setOrgName(organizationNews.getName());
        }

        model.addAttribute("examinationPoint", examinationPointList);
        model.addAttribute("name", name);
        return "certificateWeb/infoQuery/testingCentreQuery";
    }

    @Log("专家查询")
    @GetMapping("/expertQuery")
    String expertQuery() {
        return "certificateWeb/infoQuery/expertQuery";
    }

    @Log("专家条件查询")
    @PostMapping("/expertNameQuery")
    @ResponseBody
    Result<?> expertNameQuery(Model model, String type, String name, String current, String number) {
        Map map = new HashMap();
        if (type != null) {
            map.put("type", type);
        } else {
            map.put("type", null);
        }
        if (name.equals("")) {
            name = null;
        }
        map.put("name", name);
        Page<ExpertsVo> expertsVo = expertsService.selectListPage(Integer.parseInt(current), Integer.parseInt(number), map);

        List list = new ArrayList();
        for (int i = 0; i < expertsVo.getRecords().size(); i++) {
            ExpertsVo obj = (ExpertsVo) expertsVo.getRecords().get(i);
            if (obj.getKpointsId() != null) {
                KnowledgePointsDO knowledgePointsDO = knowledgePointsService.selectById(obj.getKpointsId());
                if (knowledgePointsDO != null) {
                    obj.setKpointsName(knowledgePointsDO.getName());
                }
            }
            list.add(obj);
        }
        expertsVo.setRecords(list);
        return Result.ok(expertsVo);
    }

    @Log("成绩查询页面")
    @GetMapping("/gradeQuery")
    String gradeQuery() {
        return "certificateWeb/personalCenter/gradeQuery";
    }

    /**
     * 不需要简历投递收集信息
     * @return
     */
    @GetMapping("/resumeCollect")
    @ResponseBody
    @ApiImplicitParams({@ApiImplicitParam(name = TOKEN_TAG, value = TOKEN_TAG, paramType = "header")})
    public ApiResult<?> resumeCollect(PeixResumeCollectDO peixResum,@RequestHeader(value = TOKEN_TAG, required = false) String token) {

        UserDO user = this.getClientUser(token);
        if(user==null){
            return ApiResult.invalid();
        }
        peixResum.setUserId(user.getId());
        peixResum.setCreateTime(new Date());
        boolean b=  peixResumeCollectService.insert(peixResum);
        if(b){
            return ApiResult.success();
        }
        return ApiResult.fail();

    }
    /**
     * 判断用户是否完善简历
     * @return
     */
    @GetMapping("/isResumeUser")
    @ResponseBody
    @ApiImplicitParams({@ApiImplicitParam(name = TOKEN_TAG, value = TOKEN_TAG, paramType = "header")})
    public Result<?> isResumeUser(@RequestHeader(value = TOKEN_TAG, required = false) String token) {
        UserDO user = this.getClientUser(token);
        if(user==null){
            return Result.fail("出现错误了，请重新登录再试！");
        }
        ResumesDO resumesDO = resumesService.findOneByKv("user_id",user.getId());

        if(resumesDO!=null){
            return Result.ok(1);
        }
        return Result.ok(2);
    }


    /**
     * 判断用户是否填写过不需要推荐就业的反馈信息
     * @return
     */
    @GetMapping("/feedbackList")
    @ResponseBody
    @ApiImplicitParams({@ApiImplicitParam(name = TOKEN_TAG, value = TOKEN_TAG, paramType = "header")})
    public Result<?> feedbackList(@RequestHeader(value = TOKEN_TAG, required = false) String token) {
        UserDO user = this.getClientUser(token);
        if(user==null){
            return Result.fail("出现错误了，请重新登录再试！");
        }

        PeixResumeCollectDO peixResumeCollectDO=  peixResumeCollectService.findOneByKv("user_id",user.getId());
        if(peixResumeCollectDO!=null){
            return Result.ok(1);
        }
        return Result.ok(2);
    }



    @Log("获取站点申请草稿")
    @PostMapping("findOrgRolesInfo")
    @ResponseBody
    @RequiresAuthentication
    @ApiImplicitParams({@ApiImplicitParam(name = TOKEN_TAG, value = TOKEN_TAG, paramType = "header")})
    ApiResult<Object> findOrgRolesInfo(@RequestHeader(value = TOKEN_TAG, required = false) String token,String profileName) {
        UserDO user = this.getClientUser(token);
        if (user == null) {
            return ApiResult.invalid();
        }
        Map map = new HashMap();
        int roleType=5;
        if(profileName.equals("产后恢复职业技能等级证书"))
            roleType=6;
        OrganizationRolesDO orgRole = organizationRolesService.findOneByKv("applicant_id", user.getId(),"role_type",roleType);
        if (orgRole != null) {
            OrganizationNewsDO orgNews = organizationNewsService.selectById(orgRole.getOrgId());
            map.put("orgRole", orgRole);
            map.put("orgNews", orgNews);
        } else {
            map.put("orgRole", null);
            map.put("orgNews", null);
        }

        return ApiResult.success(map);
    }

    @Log("获取培训站点申请草稿")
    @PostMapping("findTrainInfo")
    @ResponseBody
    @RequiresAuthentication
    @ApiImplicitParams({@ApiImplicitParam(name = TOKEN_TAG, value = TOKEN_TAG, paramType = "header")})
    ApiResult<Object> findTrainInfo(@RequestHeader(value = TOKEN_TAG, required = false) String token) {
        UserDO user = this.getClientUser(token);
        if (user == null) {
            return ApiResult.invalid();
        }
        Map map = new HashMap();
        TrainInfoDO trainInfoDO = trainInfoService.findOneByKv("create_user",user.getId(),"state",0);
        if (trainInfoDO != null) {
            map.put("trainInfoDO", trainInfoDO);
        } else {
            map.put("trainInfoDO", null);
        }

        return ApiResult.success(map);
    }


    @Log("站点申请页面")
    @GetMapping("testingCentreApplyFor")
    String testingCentreApplyFor(Model model, Integer type,String profileName) {

        Wrapper<ConsultationsDO> consultationsDOWrapper = new EntityWrapper<ConsultationsDO>().orderBy("creater_date", false);
        consultationsDOWrapper.eq("first_column", "证书考试门户");
        consultationsDOWrapper.eq("state", 1);
        consultationsDOWrapper.eq("second_column", "考核点申请模板"); //只查询1条
        if(type==6){
            consultationsDOWrapper.eq("title", "产后恢复考核工作承诺书");
        }else{
            consultationsDOWrapper.eq("title", "幼儿照护考核工作承诺书");
        }

        List<ConsultationsDO> consultationsDOList = consultationsService.selectList(consultationsDOWrapper);
        model.addAttribute("consultations", consultationsDOList);
        model.addAttribute("roleType", type);
        model.addAttribute("profileName",profileName);

        //获取站点申请截止时间
        Map maps = new HashMap();
        maps.put("name", "考核站点申请截止时间");
        maps.put("type", "application_end_time");
        String applicationEndTime = dictService.selDicBy(maps);
        model.addAttribute("applicationEndTime", applicationEndTime);
        //考核站点申请截止标语
        Map mapss = new HashMap();
        mapss.put("name", "考核站点申请截止标语");
        mapss.put("type", "application_slogan");
        String applicationSlogan = dictService.selDicBy(mapss);
        model.addAttribute("applicationSlogan", applicationSlogan);
        return "certificateWeb/stationApplyFor/testingCentreApplyFor";
    }
    @Log("表单填写页面")
    @GetMapping("infoMain")
    String infoMain(Model model,Long infoId) {
        InfoStoreDO infoStoreDO = infoStoreService.selectById(infoId);
        if(infoStoreDO==null){
            return null;
        }
        if(infoStoreDO.getEndTime().getTime()-new Date().getTime()<=0 || infoStoreDO.getStartTime().getTime()-new Date().getTime()>0){
            model.addAttribute("isClose",1);
        }else{
            model.addAttribute("isClose",0);
        }
        model.addAttribute("infoStoreDO",infoStoreDO);
        return "certificateWeb/info/infoMain";
    }

    @Log("表单模板列表")
    @PostMapping("findInfoModelList")
    @ResponseBody
    @RequiresAuthentication
    @ApiImplicitParams({@ApiImplicitParam(name = TOKEN_TAG, value = TOKEN_TAG, paramType = "header")})
    ApiResult<?> findInfoModelList(@RequestHeader(value = TOKEN_TAG, required = false) String token,Long infoStoreId) {
        UserDO user = this.getClientUser(token);
        if (user == null) {
            return ApiResult.fail();
        }
        Wrapper<InfoModelDO> infoModelDOWrapper = new EntityWrapper<InfoModelDO>().orderBy("sort");
        infoModelDOWrapper.eq("info_store_id",infoStoreId);
        List<InfoModelDO> infoModelList = infoModelService.selectList(infoModelDOWrapper);
        InfoCollectDO infoCollectDO = infoCollectService.findOneByKv("user_id",user.getId(),"info_store_id",infoStoreId,"status","0");
        Map map = new HashMap();
        map.put("infoModelList",infoModelList);
        if(infoCollectDO!=null){
            map.put("infoCollect",infoCollectDO);
        }else{
            map.put("infoCollect",null);
        }
        return ApiResult.success(map);
    }



    @Log("培训站点申请页面")
    @GetMapping("testingCentreApplyForPx")
    String testingCentreApplyForPx(Model model, Integer type) {

        //获取站点申请截止时间
        Map maps = new HashMap();
        maps.put("name", "培训基地申请截止时间");
        maps.put("type", "train_end_time");
        String applicationEndTime = dictService.selDicBy(maps);
        model.addAttribute("applicationEndTime", applicationEndTime);
        //考核站点申请截止标语
        Map mapss = new HashMap();
        mapss.put("name", "培训基地详申请截止标语");
        mapss.put("type", "train_slogan");
        String applicationSlogan = dictService.selDicBy(mapss);
        model.addAttribute("applicationSlogan", applicationSlogan);
        Map mapdic=new HashMap();
        mapdic.put("Type","commitment");
        List<DictDO> doList=  dictService.selectListBy(mapdic);
        if(doList.size()>0){
            model.addAttribute("commitment", doList.get(0).getValue());
        }else {
            model.addAttribute("commitment", "未设置");
        }

        return "certificateWeb/stationApplyFor/testingCentreApplyForPx";
    }


    ApiResult<?> selOrgInfo() {
        return ApiResult.success();
    }

    @Log("信息录入页面")
    @GetMapping("infoEnter")
    String infoEnter(Model model, String chatchId) {
        model.addAttribute("chatchId", chatchId);
        return "certificateWeb/onLineApply/infoEnter";
    }


    @Log("认证批次列表")
    @GetMapping("selectBatchList")
    @ResponseBody
    Result<?> selectBatchList(String current, String number) {
        Page<CertificationBatchDO> page = certificationBatchService.findListPage(Integer.parseInt(current), Integer.parseInt(number));
        return Result.ok(page);
    }

    @Log("批次介绍页面")
    @GetMapping("introduce")
    String introduce(Model model, String batchId) {
        CertificationBatchDO certificationBatch = certificationBatchService.selectById(batchId);
        CertificateNewsDO certificateNews = certificateNewsService.selectById(certificationBatch.getNewsId());
        CertificateProfileDO certificateProfile = certificateProfileService.selectById(certificationBatch.getProfileId());
        certificateNews.setProfileName(certificateProfile.getName());
        model.addAttribute("batch", certificationBatch);
        model.addAttribute("news", certificateNews);
        model.addAttribute("batchId", batchId);
        return "certificateWeb/onLineApply/introduce";
    }

    @Log("在线缴费")
    @GetMapping("/onLinePay")
    String onLinePay(Model model, String signId) {
        if (StringUtils.isNotBlank(signId)) {
            model.addAttribute("examFee", stuSignUpService.selByExamFee(Long.parseLong(signId)));
        } else {
            model.addAttribute("examFee", null);
        }
        model.addAttribute("signId", signId);
        return "certificateWeb/onLineApply/onLinePay";
    }

    @Log("跳转报名记录页面")
    @GetMapping("/findApplyExam")
    String findApplyExam() {
        return "certificateWeb/personalCenter/findApplyExam";
    }

    @Log("报名考试信息查看")
    @GetMapping("applyExam")
    String applyExam(Model model, String signId, String chatchId) {
        StuSignUpDO stuSignUp = stuSignUpService.selectById(signId);
        if (stuSignUp != null) {
            CertificationBatchDO certificationBatch = certificationBatchService.selectById(stuSignUp.getCbatchId());
            stuSignUp.setCbatchName(certificationBatch.getName());
        }
        model.addAttribute("chatchId", chatchId);
        model.addAttribute("signId", signId);
        model.addAttribute("stuSignUp", stuSignUp);
        return "certificateWeb/onLineApply/applyExam";
    }


    @Log("资料下载")
    @GetMapping("/dataDownload")
    String dataDownload() {
        return "certificateWeb/dataDownload/dataDownload";
    }

    @Log("资料文库详情")
    @GetMapping("/dataDetail")
    String dataDetail(Model model, Long id) {

        ConsultationsDO consultations = consultationsService.selectById(id);
        consultations.setAccessNumber(consultations.getAccessNumber() + 1);
        consultationsService.updateById(consultations);
        model.addAttribute("consultations", consultations);
        return "certificateWeb/dataDownload/dataDetail";
    }


    @Log("资料文库：职业技能等级标准")
    @GetMapping("/dataDownload/skillLeve")
    String skillLeve() {
        return "certificateWeb/dataDownload/skillLeve";
    }

    @Log("资料文库：教材配套资源")
    @GetMapping("/dataDownload/teaching")
    String teaching() {
        return "certificateWeb/dataDownload/teaching";
    }

    @Log("资料文库：考核评分标准")
    @GetMapping("/dataDownload/scoreCriteria")
    String scoreCriteria() {
        return "certificateWeb/dataDownload/scoreCriteria";
    }

    @Log("资料文库：考评标准")
    @GetMapping("/dataDownload/evaluationCriteria")
    String evaluationCriteria() {
        return "certificateWeb/dataDownload/evaluationCriteria";
    }

    @Log("资料文库：课程标准")
    @GetMapping("/dataDownload/courseCriteria")
    String courseCriteria() {
        return "certificateWeb/dataDownload/courseCriteria";
    }

    @Log("资料文库：操作手册")
    @GetMapping("/dataDownload/operationManual")
    String operationManual() {
        return "certificateWeb/dataDownload/operationManual";
    }

    @Log("资料文库：其他资料")
    @GetMapping("/dataDownload/otherData")
    String otherData() {
        return "certificateWeb/dataDownload/otherData";
    }


    @Log("成绩分析")
    @GetMapping("/gradeAnalyze")
    String gradeAnalyze() {
        return "certificateWeb/workNews/gradeAnalyze";
    }

    @Log("考试批次查看-未分页")
    @PostMapping("/eBatchSel")
    @ResponseBody
    Result<?> eBatchSel() {
        Wrapper<ExaminationBatchDO> wrapper = new EntityWrapper<>();
        wrapper.eq("state", 5);
//		wrapper.notIn("state", 2);
//		wrapper.notIn("state", 3);
//		wrapper.notIn("state", 4);
//		wrapper.notIn("state", 9);

        List<ExaminationBatchDO> eBatchList = examinationBatchService.selectList(wrapper);

        return Result.ok(eBatchList);
    }

    @Log("成绩分析接口")
    @PostMapping("/findAnalyze")
    @ResponseBody
    Result<?> findAnalyze(String eBatchId) {

        if (eBatchId.equals("")) {
            eBatchId = "0";
        }

        List reList = new ArrayList();
        ExaminationBatchDO examinationBatchDO = examinationBatchService.selectById(Long.parseLong(eBatchId));

        List<String> sList = Arrays.asList("北京市", "天津市", "上海市", "重庆市", "河北省", "河南省", "云南省", "辽宁省", "黑龙江省", "湖南省", "安徽省", "山东省", "新疆维吾尔自治区",
                "江苏省", "浙江省", "江西省", "湖北省", "广西壮族自治区", "甘肃省", "山西省", "内蒙古自治区", "陕西省", "吉林省", "福建省", "贵州省", "广东省", "青海省", "西藏自治区", "四川省",
                "宁夏回族自治区", "海南省", "台湾省", "香港特别行政区", "澳门特别行政区");
        for (int i = 0; i < sList.size(); i++) {

            Map map = new HashMap();
            map.put("province", sList.get(i));//省份
            Double maxScore = 0.00;//定义一个最高分
            Double avg = 0.00; //定义一个平均分
            Double pro = 0.00; //定义一个通过率
            //省份所有考点id
            List<Long> orgIds = organizationNewsService.selOrgProvince(sList.get(i));
            if (orgIds != null && orgIds.size() > 0) {
                for (int j = 0; j < orgIds.size(); j++) {
                    if (examinationBatchDO != null) {
                        //考点下该认证批次所有考生
                        List<StuSignUpDO> stuSignUpDOS = stuSignUpService.findByKv("org_id", orgIds.get(j), "cbatch_id", examinationBatchDO.getCbatchId());
                        if (stuSignUpDOS != null && stuSignUpDOS.size() > 0) {
                            Double total = 0.00; //定义成绩总和
                            Double pass = 0.00;  //定义通过人数
//							List<ExaminationResultsDO> eResult = examinationResultsService.findByKv("ebatch_id" , eBatchId);
                            for (int n = 0; n < stuSignUpDOS.size(); n++) {
                                //查询考生对应的考试成绩
                                ExaminationResultsDO examinationResultsDO = examinationResultsService.findOneByKv("cbatch_id", examinationBatchDO.getCbatchId(), "ebatch_id", examinationBatchDO.getId(), "stu_sign_id", stuSignUpDOS.get(n).getUserId());
                                if (examinationResultsDO != null) {
                                    //查询最高分
                                    if (examinationResultsDO.getTotalScore() > maxScore) {
                                        maxScore = examinationResultsDO.getTotalScore();
                                    }
                                    //查询计算平均分
                                    total = total + examinationResultsDO.getTotalScore();
                                    avg = total / stuSignUpDOS.size();

                                    //成绩分数大于合格分数 通过人数+1
                                    if (examinationResultsDO.getTotalScore() >= examinationBatchDO.getPassMark()) {
                                        pass = pass + 1;
                                    }
                                    //计算通过率
                                    pro = (pass / stuSignUpDOS.size()) * 100;

                                }
                            }
                        }
                    }
                }
            }
            map.put("max", maxScore);//最高分
            map.put("avg", avg); //平均分
            map.put("ps", pro);  //通过率

            reList.add(map);
        }

        return Result.ok(reList);
    }


    @Log("标准信息详情")
    @GetMapping("/standardDetail")
    String standardDetail() {
        return "certificateWeb/workNews/standardDetail";
    }

    @Log("关于我们")
    @GetMapping("/certificateWeb")
    String certificateWeb() {
        return "certificateWeb/about";
    }

    /**
     * 登录微信扫码登录跳转
     * @param model
     * @return
     */
    @Log("跳转登录页面")
    @GetMapping("/loginWeb")
    String loginWeb(Model model) {
        String codeimg=null;

        try {
            //配置微信回调
            String urlString = URLEncoder.encode("https://www.jz1x.com/jzApi/wximgCode/wxlogCode", "utf-8");
            codeimg="https://open.weixin.qq.com/connect/qrconnect?appid=wxa5b743d1daed59cc&redirect_uri="+urlString+"&response_type=code&scope=snsapi_login&state=e97555458779708b99b9d40cb49f54245c7500e536445d32#wechat_redirect";

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        //注册须知
        Wrapper<ConsultationsDO> consultationsDOWrapper = new EntityWrapper<ConsultationsDO>().orderBy("creater_date", false);
        consultationsDOWrapper.eq("first_column", "证书考试门户");
        consultationsDOWrapper.eq("state", 1);
        consultationsDOWrapper.eq("second_column", "注册须知").last("limit 1"); //只查询1条

        List<ConsultationsDO> consultationsDOList = consultationsService.selectList(consultationsDOWrapper);
        model.addAttribute("consultations", consultationsDOList);
        model.addAttribute("url", codeimg);

        return "certificateWeb/loginWeb";
    }


    /**
     * 培训就业账户判断
     * @param username
     * @return
     */
    @Log("跳转到指定页面")
    @GetMapping("/studyLogin")
        String loginWeb(Model model,String username) {

        //注册须知
        Wrapper<PeixunStudyDO> wrapper = new EntityWrapper<PeixunStudyDO>();
        wrapper.eq("user_name", username); //只查询1条

        List<PeixunStudyDO> consultationsDOList = peixunStudyService.selectList(wrapper);

        if(consultationsDOList.size()>0){
            return "cultivateWeb/login";
        }


        return "cultivateWeb/login";
    }

    /**
     * 金职登录接口
     * @param req
     * @param username
     * @param password
     * @return
     */
    @Log("提交登录信息")
    @PostMapping("/sendLogin")
    @ResponseBody
    Result<?> sendLogin(HttpServletRequest req, String username, String password) {

        Map m = new HashMap();
        m.put("username",username);
        if(!userService.exist(m)){
            username = userService.findOneByKv("mobile",username).getUsername();
        }

        UsernamePasswordToken token = new UsernamePasswordToken(username, password);
        //token.setRememberMe(false);//记住我是可选项，但只有会话缓存到redis等持久存储才能真正记住
        Subject subject = SecurityUtils.getSubject();
        try {
            subject.login(token);
            UserDO userDO = (UserDO) subject.getPrincipals().getPrimaryPrincipal();
            //根据手机号码生成自定义登录态
            TokenVO returnToken = userService.getToken(userDO.getMobile());

            //将生成的登录态和手机号码关联，并存到缓存中
            Map cache = new HashMap();
            cache.put("mobile", userDO.getMobile());
            EhCacheUtil.put(returnToken.getToken(), cache);
            //返回登录态和用户信息
            Map<String, Object> map = new HashMap<>();
            map.put("token", returnToken.getToken());
            map.put("userName", userDO.getUsername());
            map.put("type", userDO.getType());
            map.put("uName", userDO.getName());
            List<MsgDO> msg = msgService.findByKv("state", 0, "userId", userDO.getId(), "type", 0);
            List<MsgDO> msg1 = msgService.findByKv("state", 0, "userId", userDO.getId(), "type", 1);
            map.put("unreadNum0", msg.size());
            map.put("unreadNum1", msg1.size());
            req.getSession().setAttribute("userName", userDO.getUsername());

            return Result.ok(map);
        } catch (AuthenticationException e) {
            return Result.build(EnumErrorCode.userLoginFail.getCode(), EnumErrorCode.userLoginFail.getMsg());
        }
    }

    @Log("跳转注册页面")
    @GetMapping("/registerWeb")
    String registerWeb(Model model) {
        //注册须知
        Wrapper<ConsultationsDO> consultationsDOWrapper = new EntityWrapper<ConsultationsDO>().orderBy("creater_date", false);
        consultationsDOWrapper.eq("first_column", "证书考试门户");
        consultationsDOWrapper.eq("state", 1);
        consultationsDOWrapper.eq("second_column", "注册须知").last("limit 1"); //只查询1条

        List<ConsultationsDO> consultationsDOList = consultationsService.selectList(consultationsDOWrapper);

        model.addAttribute("consultations", consultationsDOList);
        return "certificateWeb/registerWeb";
    }

    /**
     * 微信扫码登录
     * @param model
     * @return
     */
    @Log("跳转到微信扫码登录")
    @GetMapping("/scanCode")
    String scanCode(Model model) {
        String codeimg=null;

        try {
            //微信回调
            String urlString = URLEncoder.encode("https://www.jz1x.com/jzApi/wximgCode/wxlogCode", "utf-8");
            codeimg="https://open.weixin.qq.com/connect/qrconnect?appid=wxa5b743d1daed59cc&redirect_uri="+urlString+"&response_type=code&scope=snsapi_login&state=e97555458779708b99b9d40cb49f54245c7500e536445d32#wechat_redirect";

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        //注册须知
        Wrapper<ConsultationsDO> consultationsDOWrapper = new EntityWrapper<ConsultationsDO>().orderBy("creater_date", false);
        consultationsDOWrapper.eq("first_column", "证书考试门户");
        consultationsDOWrapper.eq("state", 1);
        consultationsDOWrapper.eq("second_column", "注册须知").last("limit 1"); //只查询1条

        List<ConsultationsDO> consultationsDOList = consultationsService.selectList(consultationsDOWrapper);

        model.addAttribute("consultations", consultationsDOList);
        model.addAttribute("url", codeimg);
        return "certificateWeb/scanDode";
    }

    @Log("跳转手机注册页面")
    @GetMapping("/registerMobileWeb")
    String registerMobileWeb(Model model) {
        //注册须知
        Wrapper<ConsultationsDO> consultationsDOWrapper = new EntityWrapper<ConsultationsDO>().orderBy("creater_date", false);
        consultationsDOWrapper.eq("first_column", "证书考试门户");
        consultationsDOWrapper.eq("state", 1);
        consultationsDOWrapper.eq("second_column", "注册须知").last("limit 1"); //只查询1条

        List<ConsultationsDO> consultationsDOList = consultationsService.selectList(consultationsDOWrapper);

        model.addAttribute("consultations", consultationsDOList);
        return "certificateWeb/registerMobileWeb";
    }



    @Log("提交注册")
    @PostMapping("/sendRegister")
    @ResponseBody
    Result<?> sendRegister(String name, String password, String mobile, String code) {
        //查询手机号是否注册
        Wrapper<UserDO> wrapper = new EntityWrapper();
        wrapper.eq("mobile", mobile);
        UserDO user = userService.selectOne(wrapper);
        if (user != null) {
            throw new IFastApiException(ApiEnumError.mobileAlreadyReg.getCodeStr());
        }
        UserDO users = userService.findOneByKv("username", name);
        if (users != null) {
            throw new IFastApiException(ApiEnumError.USERNAMEEXISTED.getCodeStr());
        } else {
            //校验验证码
            try {
                smsService.verify(O_REG_SMS_PREFIX, mobile, code);
            } catch (Exception e) {
                throw new IFastApiException(ApiEnumError.apiSmsCodeInvalid.getCodeStr());
            }
            UserDO userDO = new UserDO();
            userDO.setPassword(password);
            userDO.setUsername(name);
            userDO.setWxId(103);
            userDO.setMobile(mobile);

            userDO.setMoney(BigDecimal.valueOf(0.0));//默认0元
            userDO.setGmtCreate(new Date());
            userDO.setStatus(1);//默认正常
            userDO.setSex(0L);//默认未知
            OrgRelationDO orgRelation = orgRelationService.findOneByKv("correlation_phone", mobile);
            if (orgRelation != null) {
                OrganizationNewsDO orgNews = organizationNewsService.selectById(orgRelation.getCorrelationOrgId());
                if (orgNews != null) {
                    userDO.setOrgName(orgNews.getName());
                    userDO.setOrgId(orgNews.getId());
                }
                userDO.setType(1);
            } else {
                userDO.setType(0);//默认个人会员
            }

            boolean b = userService.insert(userDO);
            if (b) {
                userService.insertUserRole(56L, userDO.getId());

                //查询用户是否是实习单位
                if (orgRelation != null) {
                    OrganizationNewsDO orgNews = organizationNewsService.selectById(orgRelation.getCorrelationOrgId());
                    if (orgNews != null) {
                        orgNews.setLeadingCadreId(userDO.getId());
                        organizationNewsService.updateById(orgNews);
                    }
                    //查询关联的机构
                    OrganizationNewsDO orgNews1 = organizationNewsService.selectById(orgRelation.getOrgId());
                    if (orgNews1 != null) {
                        orgNews1.setImportActivateNum(orgNews1.getImportActivateNum() + 1);
                        organizationNewsService.updateById(orgNews1);
                    }
                }

            }
            return Result.ok();
        }
    }

    @Log("忘记密码")
    @GetMapping("/forgetPass")
    String forgetPass() {  //忘记密码
        return "certificateWeb/forgetPass";
    }

    @Log("跳转考核站点申请记录页面")
    @GetMapping("/stationRecordList")
    String stationRecordList() {
        return "certificateWeb/personalCenter/stationRecord";
    }

    @Log("跳转表单提交记录页面")
    @GetMapping("/infoRecordList")
    String infoRecordList() {
        return "certificateWeb/personalCenter/infoRecord";
    }

    @Log("官网填写简历页面")
    @GetMapping("/isResume")
    String isResume() {
        return "certificateWeb/personalCenter/isResume";
    }


    @Log("官网填写简历页面")
    @GetMapping("/appendResume")
    String appendResume() {
        return "certificateWeb/personalCenter/appendResume";
    }

    @Log("官网查看简历页面")
    @GetMapping("/iResume")
    String iResume() {
        return "certificateWeb/personalCenter/iResume";
    }

    @Log("跳转培训站点申请记录页面")
    @GetMapping("/stationPxRecordList")
    String stationPxRecordList() {
        return "certificateWeb/personalCenter/stationPxRecord";
    }

    @Log("跳转申请记录页面")
    @GetMapping("/expertRecordList")
    String expertRecordList() {
        return "certificateWeb/personalCenter/expertRecord";
    }

    @Log("跳转个人中心页面")
    @GetMapping("/my")
    String my() {
        return "certificateWeb/personalCenter/myCenter";
    }

    @Log("跳转消息中心页面")
    @GetMapping("/message")
    @RequiresAuthentication
    String message() {
        return "certificateWeb/personalCenter/message";
    }

    @Log("跳转模拟考试页面")
    @GetMapping("/mock")
    String mock(Model model , String grade) {
        model.addAttribute("grade",grade);
        return "certificateWeb/personalCenter/mockExam";
    }

    @Log("编辑个人信息")
    @GetMapping("/editMy")
    String editMy(Model model) {
        model.addAttribute("certificateProfile", certificateNewsService.selByProfileId());
        return "certificateWeb/personalCenter/editMy";
    }

    @Log("跳转专家申请页面")
    @GetMapping("/evaluationStationApplyFor")
    String evaluationStationApplyFor(Model model, Integer type) {
        Wrapper<ConsultationsDO> consultationsDOWrapper = new EntityWrapper<ConsultationsDO>().orderBy("creater_date", false);
        consultationsDOWrapper.eq("first_column", "证书考试门户");
        consultationsDOWrapper.eq("state", 1);
        if (type == 0) {
            consultationsDOWrapper.eq("second_column", "考评员申请模板").last("limit 1"); //只查询1条
        }
        if (type == 1) {
            consultationsDOWrapper.eq("second_column", "考务员申请模板").last("limit 1"); //只查询1条
        }
        if (type == 3) {
            consultationsDOWrapper.eq("second_column", "督导员申请模板").last("limit 1"); //只查询1条
        }
        if (type == 4) {
            consultationsDOWrapper.eq("second_column", "讲师申请模板").last("limit 1"); //只查询1条
        }
        if (type == 2) {
            consultationsDOWrapper.eq("second_column", "考务技术员申请模板").last("limit 1"); //只查询1条
        }
        List<ConsultationsDO> consultationsDOList = consultationsService.selectList(consultationsDOWrapper);
        model.addAttribute("consultations", consultationsDOList);
        model.addAttribute("type", type);
        return "certificateWeb/stationApplyFor/evaluationStationApplyFor";
    }

    @Log("跳专家编辑页面")
    @GetMapping("/editExpert")
    String editExpert(Model model, String id) {
        ExpertsDO experts = expertsService.selectById(id);
        Wrapper<ConsultationsDO> consultationsDOWrapper = new EntityWrapper<ConsultationsDO>().orderBy("creater_date", false);
        consultationsDOWrapper.eq("first_column", "证书考试门户");
        consultationsDOWrapper.eq("state", 1);
        if (experts.getType() == 0) {
            consultationsDOWrapper.eq("second_column", "考评员申请模板").last("limit 1"); //只查询1条
        }
        if (experts.getType() == 1) {
            consultationsDOWrapper.eq("second_column", "考务员申请模板").last("limit 1"); //只查询1条
        }
        if (experts.getType() == 3) {
            consultationsDOWrapper.eq("second_column", "督导员申请模板").last("limit 1"); //只查询1条
        }
        if (experts.getType() == 4) {
            consultationsDOWrapper.eq("second_column", "讲师申请模板").last("limit 1"); //只查询1条
        }
        if (experts.getType() == 2) {
            consultationsDOWrapper.eq("second_column", "考务技术员申请模板").last("limit 1"); //只查询1条
        }
        List<ConsultationsDO> consultationsDOList = consultationsService.selectList(consultationsDOWrapper);
        model.addAttribute("consultations", consultationsDOList);
        UserDO user = userService.selectById(experts.getUserId());
        model.addAttribute("user", user);
        model.addAttribute("expert", experts);
        model.addAttribute("certificateProfile", certificateNewsService.selByProfileId());
        model.addAttribute("id", id);
        return "certificateWeb/stationApplyFor/editExpert";
    }



    @Log("跳转站点编辑页面")
    @GetMapping("/editStation")
    String editStation(Model model, String id) {
        OrganizationRolesDO organizationRoles = organizationRolesService.selectById(id);
        Wrapper<ConsultationsDO> consultationsDOWrapper = new EntityWrapper<ConsultationsDO>().orderBy("creater_date", false);
        consultationsDOWrapper.eq("first_column", "证书考试门户");
        consultationsDOWrapper.eq("state", 1);
        consultationsDOWrapper.eq("second_column", "考核点申请模板").last("limit 1"); //只查询1条

        List<ConsultationsDO> consultationsDOList = consultationsService.selectList(consultationsDOWrapper);
        model.addAttribute("consultations", consultationsDOList);

        OrganizationNewsDO organizationNews = organizationNewsService.selectById(organizationRoles.getOrgId());

        model.addAttribute("orgRoles", organizationRoles);
        model.addAttribute("orgNews", organizationNews);
        return "certificateWeb/stationApplyFor/editStation";
    }

    @Log("机构id查询机构信息")
    @PostMapping("findOrgById")
    @ResponseBody
    @RequiresAuthentication
    @ApiImplicitParams({@ApiImplicitParam(name = TOKEN_TAG, value = TOKEN_TAG, paramType = "header")})
    public ApiResult<?> findOrgById(@RequestHeader(value = TOKEN_TAG, required = false) String token, String orgId) {

        UserDO user = this.getClientUser(token);
        if (user == null) {
            return ApiResult.invalid();
        }
        OrganizationNewsDO orgNews = organizationNewsService.selectById(orgId);
        if (orgNews != null) {
            OrganizationRolesDO orgRole = organizationRolesService.findOneByKv("org_id", orgNews.getId(), "role_type", 5);
            if (orgRole != null) {
                orgNews.setEnclosure(orgRole.getEnclosure());
            }
        }
        return ApiResult.success(orgNews);
    }


    @Log("报名成功")
    @GetMapping("/applySuccess")
    String applySuccess(Model model, String signId, String chatchId) {
        model.addAttribute("chatchId", chatchId);
        model.addAttribute("signId", signId);
        return "certificateWeb/onLineApply/applySuccess";
    }

    @Log("查看准考证页面")
    @GetMapping("/examCard")
    String examCard(Model model, String id) {
        model.addAttribute("id", id);
        return "certificateWeb/personalCenter/ExamCard";
    }

    @Log("退出登录")
    @GetMapping("/loginOut")
    @ResponseBody
    Result<?> loginOut() {
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        return Result.ok();
    }

    @Log("机构列表接口-未分页")
    @GetMapping("/orgList")
    @ResponseBody
    Result<?> orgList() {
        Wrapper<OrganizationRolesDO> wrapper = new EntityWrapper<>();
        wrapper.eq("role_type", 5);
        wrapper.eq("checker_state", 1);
        List<OrganizationRolesDO> orgRoles = organizationRolesService.selectList(wrapper);
        for (OrganizationRolesDO orgRole : orgRoles) {
            OrganizationNewsDO orgNews = organizationNewsService.selectById(orgRole.getOrgId());
            if (orgNews != null) {
                orgRole.setOrgName(orgNews.getName());
            }
        }

        return Result.ok(orgRoles);
    }

    @Log("编辑报名信息")
    @GetMapping("/editExamRecord")
    String editExamRecord(Model model, String id) {
        StuSignUpDO stuSignUp = stuSignUpService.selectById(id);
        model.addAttribute("stuInfo", stuSignUp);
        return "certificateWeb/personalCenter/editExamRecord";
    }

    @Log("查询机构信息")
    @GetMapping("/findByOrg")
    String findByOrg(Model model, String orgId) {
        model.addAttribute("orgId", orgId);
        return "certificateWeb/personalCenter/orgInfo";
    }

    @Log("查询个人机构信息")
    @PostMapping("selPersonOrg")
    @ResponseBody
    @RequiresAuthentication
    @ApiImplicitParams({@ApiImplicitParam(name = TOKEN_TAG, value = TOKEN_TAG, paramType = "header")})
    public ApiResult<?> selPersonOrg(@RequestHeader(value = TOKEN_TAG, required = false) String token, String orgId) {

        UserDO user = this.getClientUser(token);

        OrganizationNewsDO org = organizationNewsService.selectById(orgId);
        org.setLeadingCadreName(user.getName());

        OrganizationRolesDO orgRole = organizationRolesService.findOneByKv("org_id", org.getId(), "role_type", 5);

        Map map = new HashMap();
        map.put("orgNews", org);
        map.put("orgRole", orgRole);
        return ApiResult.success(map);
    }

    @Log("编辑查询机构信息")
    @GetMapping("/editOrg")
    String editOrg(Model model, String orgId) {

        OrganizationNewsDO org = organizationNewsService.selectById(orgId);
        Wrapper<ConsultationsDO> consultationsDOWrapper = new EntityWrapper<ConsultationsDO>().orderBy("creater_date", false);
        consultationsDOWrapper.eq("first_column", "证书考试门户");
        consultationsDOWrapper.eq("state", 1);
//		if (organizationRoles.getRoleType() == 5){
        consultationsDOWrapper.eq("second_column", "考核点申请模板").last("limit 1"); //只查询1条
		/*}else if (organizationRoles.getRoleType() == 2){
			consultationsDOWrapper.eq("second_column", "考评点申请模板").last("limit 1"); //只查询1条
		}*/

        List<ConsultationsDO> consultationsDOList = consultationsService.selectList(consultationsDOWrapper);
        model.addAttribute("consultations", consultationsDOList);

        model.addAttribute("org", org);
        return "certificateWeb/personalCenter/editOrg";
    }

    @Log("保存机构信息")
    @PostMapping("/saveOrg")
    @ResponseBody
    Result<?> saveOrg(Model model, OrganizationNewsDO organizationNewsDO) {
        organizationNewsDO.setUpdateDate(new Date());
        organizationNewsService.updateById(organizationNewsDO);
        return Result.ok();
    }

    @PostMapping("/sendRegCode")
    @Log("发送注册验证短信")
    @ApiOperation(value = "发送注册验证短信", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ResponseBody
    public ApiResult<?> sendRegCode(String mobile) {
        //第一步验证手机号格式
        if (StringUtils.isBlank(mobile)) {
            return ApiResult.lack("mobile");
        }
        if (!ValidUtils.isMobile(mobile)) {
            return ApiResult.format("mobile");
        }

        Object smsDemo = EhCacheUtil.get("注册短信验证");
        if (smsDemo == null) {
            MessageplatfromDO messageplatfromDO = messageplatfromService.findOneByKv("注册短信验证");
            if (messageplatfromDO != null) {
                EhCacheUtil.put("注册短信验证", messageplatfromDO.getSmsDemo());
                smsService.sendreg(O_REG_SMS_PREFIX, mobile, messageplatfromDO.getSmsDemo());
            } else {
                return ApiResult.fail("短信模板错误，请联系管理员！");
            }
        } else {
            smsService.sendreg(O_REG_SMS_PREFIX, mobile, (String) smsDemo);
        }

        return ApiResult.success("发送成功");
    }

    /**
     * 微信扫码绑定 手机号
     * @param mobile
     * @return
     */
    @PostMapping("/sendRegCodeWx")
    @Log("发送注册验证短信")
    @ApiOperation(value = "发送注册验证短信", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ResponseBody
    public ApiResult<?> sendRegCodeWx(String mobile) {
        //第一步验证手机号格式
        if (StringUtils.isBlank(mobile)) {
            return ApiResult.lack("mobile");
        }
        if (!ValidUtils.isMobile(mobile)) {
            return ApiResult.format("mobile");
        }

        Object smsDemo = EhCacheUtil.get(mobile+"wxCode");
        if (smsDemo == null) {
            MessageplatfromDO messageplatfromDO = messageplatfromService.findOneByKv("微信绑定短信验证");
            if (messageplatfromDO != null) {
                EhCacheUtil.put(mobile+"wxCode", messageplatfromDO.getSmsDemo());
                smsService.sendreg(O_REG_SMS_PREFIX, mobile, messageplatfromDO.getSmsDemo());

            } else {
                return ApiResult.fail("短信模板错误，请联系管理员！");
            }
        } else {
            smsService.sendreg(O_REG_SMS_PREFIX, mobile, (String) smsDemo);
        }

        return ApiResult.success("发送成功");
    }



    @Log("查询对应证书的知识点")
    @GetMapping("/findKonwledge")
    @ResponseBody
    public ApiResult<?> findKonwledge(String profileId) {
        List<KnowledgePointsDO> knowList = knowledgePointsService.findByKv("profile_id", profileId, "state", 0);
        return ApiResult.success(knowList);
    }

    @Log("试点院校风采")
    @GetMapping("/schoolMien")
    String schoolMien(Model model) {
        return "certificateWeb/tradeInfo/schoolMien";
    }

    @Log("考试流程介绍")
    @PostMapping("/examIntroduce")
    @ResponseBody
    Result<?> examIntroduce() {
        ConsultationsDO conDo = consultationsService.findOneByKv("second_column", "考试流程介绍");
        return Result.ok(conDo);
    }

    /**
     * 下载导入模板
     *
     * @param response
     */
    @RequestMapping("/download")
    @ResponseBody
    public void downloadImportTemplate(HttpServletResponse response, Integer type) {
        List<TrainingBaseVo> list = new LinkedList<>();
        if (type == 5) {//导出操作
            EasyPoiUtil.exportExcel(list, "实习就业单位信息导入模板", "实习就业单位信息导入模板", TrainingBaseVo.class, "实习就业单位信息导入模板", response);
        } else {
            EasyPoiUtil.exportExcel(list, "校企合作信息导入模板", "校企合作信息导入模板", TrainingBaseVo.class, "校企合作信息导入模板", response);
        }

//		EasyPoiUtil.exportExcel(list, "实习就业单位信息导入模板", "实习就业单位信息导入模板", TrainingBaseVo.class, "实习就业单位信息导入模板", response);
    }

    /**
     * 实训基地信息导入
     *
     * @param file excel文件
     */
    @Log("实训基地信息导入")
    @PostMapping("/import")
    @ResponseBody
    @Transactional
    @ApiImplicitParams({@ApiImplicitParam(name = TOKEN_TAG, value = TOKEN_TAG, paramType = "header")})
    public ApiResult<?> importExcel(@RequestHeader(value = TOKEN_TAG, required = false) String token, @RequestParam("file") MultipartFile file) {

        UserDO user = this.getClientUser(token);
        if (user == null) {
            return ApiResult.invalid();
        }


        //---------------------------------检测导入信息及条件-----------------------------------------
        //第一步--判断文件格式
        if (!"application/vnd.ms-excel".equals(file.getContentType())) {
            return ApiResult.fail("文件格式错误，请选择.xls文件");
        }

        //第二步--解析文件获得数据
        List<TrainingBaseVo> list = EasyPoiUtil.importExcel(file, 1, 1, TrainingBaseVo.class);
        if (list.size() == 0) {
            return ApiResult.fail("Excel数据为空，请完善");
        }

        //---------------------------------验证数据并导入-----------------------------------------
        //数据该表第三行，第一行标题，第二行表头
        int startRow = 3;
        int cout = 1;//错误信息计数
        List<OrganizationNewsDO> bankDOList = new ArrayList<>();
        List<ErrorCodeVo> list1 = new ArrayList<>();
        for (int i = 0; i < list.size(); i++) {
            StringBuilder sb = new StringBuilder();
            //第一步验证是否存在空值
            if (org.apache.commons.lang.StringUtils.isBlank(list.get(i).getName())) {
                sb.append("第" + (i + startRow) + "行单位名称称未填写，请完善！" + ";");
            } else {
                if (org.apache.commons.lang.StringUtils.isBlank(list.get(i).getLeadingCadre())) {
                    sb.append("第" + (i + startRow) + "行单位负责人未填写，请完善！" + ";");
                } else {
                    if (org.apache.commons.lang.StringUtils.isBlank(list.get(i).getMobile())) {
                        sb.append("第" + (i + startRow) + "行联系电话未填写，请完善！" + ";");
                    } else if (org.apache.commons.lang.StringUtils.isBlank(list.get(i).getPracticeOrgLeadingCadre())) {
                        sb.append("第" + (i + startRow) + "行实习就业负责人未填写，请完善！" + ";");
                    } else {
                        if (org.apache.commons.lang.StringUtils.isBlank(list.get(i).getPracticeOrgMobile())) {
                            sb.append("第" + (i + startRow) + "行负责人联系电话未填写，请完善！" + ";");
                        } else {
                            if (org.apache.commons.lang.StringUtils.isBlank(list.get(i).getRecruitingNum())) {
                                sb.append("第" + (i + startRow) + "行拟招聘人数未填写，请完善！" + ";");
                            } else {
                                if (org.apache.commons.lang.StringUtils.isBlank(list.get(i).getHiring())) {
                                    sb.append("第" + (i + startRow) + "行拟招聘岗位未填写，请完善！" + ";");
                                } else {
                                    if (org.apache.commons.lang.StringUtils.isBlank(list.get(i).getEmolument())) {
                                        sb.append("第" + (i + startRow) + "行薪酬未填写，请完善！" + ";");
                                    } else {
                                        //第二步验证电话号码
                                        if (!ValidUtils.isMobile(list.get(i).getMobile())) {
                                            sb.append("第" + (i + startRow) + "行联系电话格式错误，请完善！" + ";");
                                        } else {
                                            if (!ValidUtils.isMobile(list.get(i).getPracticeOrgMobile())) {
                                                sb.append("第" + (i + startRow) + "行负责人手机号码格式错误，请完善！" + ";");
                                            } else {
                                                if (sb.length() == 0) {
                                                    //第四步排重验证（自身比较）
                                                    for (int j = 0; j < list.size(); j++) {
                                                        if (i != j) {
                                                            if (list.get(i).getName().equals(list.get(j).getName())) {
                                                                sb.append("第" + (i + startRow) + "行跟第" + (j + startRow) + "行单位名称重复，重复值：" + list.get(i).getName() + ";");
                                                            }
                                                            if (list.get(i).getLeadingCadre().equals(list.get(j).getLeadingCadre())) {
                                                                sb.append("第" + (i + startRow) + "行跟第" + (j + startRow) + "行单位负责人重复，重复值：" + list.get(i).getLeadingCadre() + ";");
                                                            }
                                                            if (list.get(i).getMobile().equals(list.get(j).getMobile())) {
                                                                sb.append("第" + (i + startRow) + "行跟第" + (j + startRow) + "行联系电话重复，重复值：" + list.get(i).getMobile() + ";");
                                                            }
                                                            if (list.get(i).getPracticeOrgLeadingCadre().equals(list.get(j).getPracticeOrgLeadingCadre())) {
                                                                sb.append("第" + (i + startRow) + "行跟第" + (j + startRow) + "行实习就业负责人重复，重复值：" + list.get(i).getPracticeOrgLeadingCadre() + ";");
                                                            }
                                                            if (list.get(i).getPracticeOrgMobile().equals(list.get(j).getPracticeOrgMobile())) {
                                                                sb.append("第" + (i + startRow) + "行跟第" + (j + startRow) + "行负责人联系电话重复，重复值：" + list.get(i).getPracticeOrgMobile() + ";");
                                                            }
                                                        }
                                                    }
                                                    //根据名字查询机构是否存在
                                                    OrganizationNewsDO orgNews = organizationNewsService.findOneByKv("name", list.get(i).getName());
                                                    if (orgNews == null) {
                                                        orgNews = new OrganizationNewsDO();
                                                        orgNews.setName(list.get(i).getName());
                                                        orgNews.setType(2);
                                                        organizationNewsService.insert(orgNews);

                                                        OrganizationRolesDO orgRole = new OrganizationRolesDO();
                                                        orgRole.setOrgId(orgNews.getId());
                                                        orgRole.setRoleType(3);
                                                        organizationRolesService.insert(orgRole);

                                                        OrgRelationDO orgRelation = new OrgRelationDO();
//														orgRelation.setOrgId();
                                                        orgRelation.setOrgUserId(user.getId());
                                                        orgRelation.setCreateTime(new Date());
                                                        orgRelation.setCorrelationOrgId(orgNews.getId());
                                                        orgRelation.setCorrelationPhone(list.get(i).getMobile());
                                                        orgRelationService.insert(orgRelation);

                                                    } else {
                                                        OrganizationRolesDO orgRole = organizationRolesService.findOneByKv("org_id", orgNews.getId(), "role_type", 3);
                                                        if (orgRole == null) {
                                                            OrganizationRolesDO orgRoles = new OrganizationRolesDO();
                                                            orgRoles.setOrgId(orgNews.getId());
                                                            orgRoles.setRoleType(3);
                                                            organizationRolesService.insert(orgRoles);
                                                        }

                                                        //查询关联表的数据是否有重复的
                                                        List<OrgRelationDO> orgRelationList = orgRelationService.findByKv("org_user_id", user.getId(), "correlation_org_id", orgNews.getId());
                                                        if (orgRelationList.size() >= 1) {
                                                            sb.append("第" + (i + startRow) + "行数据已存在，请勿重复导入");
                                                        } else {
                                                            OrgRelationDO orgRelation = new OrgRelationDO();
//															orgRelation.setOrgId();
                                                            orgRelation.setOrgUserId(user.getId());
                                                            orgRelation.setCreateTime(new Date());
                                                            orgRelation.setCorrelationOrgId(orgNews.getId());
                                                            orgRelation.setCorrelationPhone(list.get(i).getMobile());
                                                            orgRelationService.insert(orgRelation);
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }

            if (sb.length() > 0) {
                ErrorCodeVo errorCodeVo = new ErrorCodeVo();
                errorCodeVo.setSeq(cout);
                cout += 1;
                errorCodeVo.setErrorCode(sb.toString());
                list1.add(errorCodeVo);
            }
        }
        if (list1.size() == 0) {
            return ApiResult.success("成功导入" + list.size() + "条数据");
        } else {
            JSONArray jsonArray = JSONArray.parseArray(JSON.toJSONString(list1));
            //将list1存到缓存中
            EhCacheUtil.put("trainingBase" + user.getId(), jsonArray);
            return ApiResult.build(EnumErrorCode.FileImportError.getCode(), EnumErrorCode.FileImportError.getMsg());
        }
    }

    /**
     * 导出错误信息
     *
     * @param request
     * @param response
     * @throws Exception
     */
    @Log("导出错误信息")
    @GetMapping("/importError")
    @ResponseBody
    @Transactional
    @ApiImplicitParams({@ApiImplicitParam(name = TOKEN_TAG, value = TOKEN_TAG, paramType = "header")})
    public void download(HttpServletRequest request, HttpServletResponse response, @RequestHeader(value = TOKEN_TAG, required = false) String token) throws Exception {
        UserDO user = this.getClientUser(token);
        // 告诉浏览器用什么软件可以打开此文件
        response.setHeader("content-Type", "application/vnd.ms-excel");
        // 下载文件的默认名称
        response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode("实习就业单位信息导入错误信息", "UTF-8") + ".xls");
        //编码
        response.setCharacterEncoding("UTF-8");
        String jsonArray = EhCacheUtil.get("trainingBase" + user.getId()).toString();
        JSONArray arrayList = JSONArray.parseArray(jsonArray);
        //转换为目标对象list
        List<ErroeDownVo> groupList = JSONObject.parseArray(arrayList.toJSONString(), ErroeDownVo.class);
        Workbook workbook = ExcelExportUtil.exportExcel(new ExportParams(), ErroeDownVo.class, groupList);
        workbook.write(response.getOutputStream());

    }


}
